package org.example.servlet;

import org.example.entity.Reply;
import org.example.entity.User;
import org.example.service.ReviewService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;

@WebServlet("/add-reply")
public class AddReplyServlet extends HttpServlet {
    private final ReviewService reviewService = new ReviewService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            User user = (User) req.getSession().getAttribute("user");
            if (user == null) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "请先登录");
                return;
            }

            int reviewId = Integer.parseInt(req.getParameter("reviewId"));
            String content = req.getParameter("content");

            Reply reply = new Reply();
            reply.setReviewId(reviewId);
            reply.setUserId(user.getId());
            reply.setUsername(user.getUsername());
            reply.setContent(content);
            reply.setCreateTime(new Timestamp(new Date().getTime()));

            boolean success = reviewService.addReply(reply);

            if (success) {
                resp.setContentType("application/json");
                resp.getWriter().write("{\"success\": true}");
            } else {
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "添加回复失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器错误");
        }
    }
}